<template>
  <!--  <div>-->
  <div class="canvas-wrapper">
    <div class="canvas-container">
  <!--    <canvas id="myCanvas" width="1200px" height="565.6px" @mousemove="updateXY"  border="2px solid red;"></canvas>-->
      <canvas id="backgroundCanvas" width="1500" height="680"></canvas>
      <canvas id="myCanvas" width="1500" height="680" @mousemove="updateXY"></canvas>
  <div v-if="showTooltip" :style="{top: tooltipY + 'px', left: tooltipX + 'px'}" class="tooltip">
    {{ tooltipContent }}
<!--    {{ formattedTooltipContent(tooltipContent) }}-->
  </div>
    </div>
  </div>
  <!--    <canvas id="myCanvas" width="3268" height="1480" @mousemove="updateXY"  border="2px solid red;"></canvas>-->
  <!--  </div>-->
</template>

<script>
import AddOrUpdate from './lableonline-add-or-update'
export default {
  data () {
    return {
      timer: null,
      dataForm: {
        key: ''
      },
      x: 0,
      y: 0,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      enabledMapLocalpaths: '',
      showTooltip: false,
      tooltipX: 0,
      tooltipY: 0,
      tooltipContent: '',
      oldDataListInfo: [],  // 用于保存前一个状态的数据
    }
  },
  components: {
    AddOrUpdate
  },
  computed: {},
  mounted () {
    // this.showPosInfoData()

    this.renderBackgroundCanvas();
    // 页面加载后
    // 1.在执行定时器前先执行一次获取接口数据的操作函数, 否则接口会1秒钟后才调用
    // 2.为了避免退出当前页面后,在其他页面也继续调用接口,退出前需要清除定时器.
    this.show();

    // 每 3 秒执行一次 show 方法
    this.timer = setInterval(() => {
      this.show();
    }, 3000);
    // this.timer = setInterval(() => {
    //   setTimeout(this.show, 0)
    // }, 20000)
  },
  beforeRouteLeave (to, from, next) {
    // 在离开当前路由之前清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    next();
  },
  activated () {
    this.dataListLoading = true;
    // 在另一个页面中获取已启用地图的mapLocalpaths
    this.enabledMapLocalpaths = JSON.parse(localStorage.getItem('enabledMapLocalpaths'));
    // console.log("enabledMapLocalpaths")
    // console.log(this.enabledMapLocalpaths); // 这里将会输出所有已启用地图的mapLocalpath数组
    this.show()
    this.dataListLoading = false;
  },
  methods: {
    //测试ws数据
    showPosInfoData(){
      // let URL = "ws://10.143.7.73:8089/renren-fast/websocket/font";
      // let URL = "ws://localhost:8089/renren-fast/websocket/allPosInfo";
      let URL = "ws://10.143.7.73:8089/renren-fast/websocket/allPosInfo";
      let ws = new WebSocket(URL);
      ws.onmessage = evt => {    //后端发来的消息接收（注意数据放在evt的data中并且是个JSON字符串，需要parse成JSON对象去使用）
        //let hhlist = JSON.parse(evt);

        console.log("接收中。。。")
        console.log(evt.data)
        //evt.data格式为：{"板材切割中心3#切割机.deviceProcessStatus":"6","板材切割中心3#切割机.deviceCutStatus":"1","板材切割中心3#切割机.deviceMachineSpeed":"0","板材切割中心3#切割机.deviceLocation":"0","板材切割中心3#切割机.deviceStatus":"0"}
        console.log('接收完成')
        //具体业务逻辑
        const messageData = JSON.parse(evt.data);
        this.updateMessageData(messageData);

      }
      ws.onclose = function () {
        // 关闭 websocket
        console.log('连接已关闭...')
      }
      // 路由跳转时结束websocket链接
      this.$router.afterEach(function () {
        ws.close()
      })
    },
    renderBackgroundCanvas() {
      const c = document.getElementById('backgroundCanvas');
      const ctx = c.getContext('2d');
      const img = new Image();
      img.src = this.enabledMapLocalpaths;
      img.onload = function() {
        ctx.drawImage(img, 0, 0, c.width, c.height);
      };
    },
    updateXY (event) {
      this.x = event.offsetX;
      this.y = event.offsetY;
      this.checkPointNearby(event.target);
    },
    checkPointNearby (target) {
      for (let point of this.dataListInfo) {
        const distance = Math.sqrt(Math.pow((this.x - point.posX), 2) + Math.pow((this.y - point.posY), 2));
        if (distance <= 5) { // 根据你的点的大小，5可能需要调整
          this.showTooltip = true;
          this.tooltipX = this.x + 10; // 在鼠标右侧稍微偏移
          this.tooltipY = this.y + 10; // 在鼠标下方稍微偏移
          this.tooltipContent = `Card ID: ${point.cardId}\nName: ${point.personName}`;
          target.style.cursor = 'pointer'; // 直接在此设置鼠标样式
          return;
        }
      }
      this.showTooltip = false;  // 如果没有点在附近，隐藏tooltip
      target.style.cursor = 'default'; // 直接在此设置鼠标样式
    },
    show () {
      // this.getArea()
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl('/labonin/lableonlineinfo/iswork'),
        async: false,
        method: 'get'
      }).then(({data}) => {
        this.oldDataListInfo = this.dataListInfo; // 保存旧数据
        this.dataListInfo = data;
        console.log(this.oldDataListInfo)
        // this.areaList = data.page.list
        // console.log('ok')
        var json = data;
        console.log(json)
        var query1 = json.filter(function (i) {
          return i.isWork == 1;
        })
        // console.log(query1)
        var query2 = json.filter(function (i) {
          return i.isWork == 0;
        })
        // console.log(query2)

        var query3 = json.filter(function (i) {
          return i.isWork == 2;
        })
        // console.log("3")
        // console.log(query3)

        var arr = [];
        for (let i in query1) {
          arr.push(query1[i]);
        }
        var posx = arr.map(item => {
          // 每一项的id
          return item.posX
        });
        var posy = arr.map(item => {
          // 每一项的id
          return item.posY
        });
        // console.log(posx)

        var arr2 = [];
        for (let i in query2) {
          arr2.push(query2[i]);
        }
        var posx1 = arr2.map(item => {
          // 每一项的id
          return item.posX
        });
        var posy1 = arr2.map(item => {
          // 每一项的id
          return item.posY
        });
        // console.log(posx1)

        //异常标签代码，未测试
        var arr3 = [];
        for (let i in query3) {
          arr3.push(query3[i]);
        }
        var posx2 = arr3.map(item => {
          // 每一项的id
          return item.posX
        });
        var posy2 = arr3.map(item => {
          // 每一项的id
          return item.posY
        });
        // console.log("-----------------")
        // console.log(posx2)

        var c = document.getElementById('myCanvas');
        const img = new Image();

        const ctx = c.getContext('2d');
        ctx.strokeStyle = '#0000ff';

        // 动手
        // img.src = 'static/images/3.jpg';
        img.src = this.enabledMapLocalpaths;
        // 当图片加载完再动手
        img.onload = function () {
          // 画布大小和图片尺寸不一样算好比例
          const cWidth = c.width;
          const cHeight = c.height;
          const imgWidth = img.naturalWidth;
          const imgHeight = img.naturalHeight;
          // console.log("img")
          // console.log(imgWidth)
          // console.log(imgHeight)
          const zoom = {
            width: cWidth / imgWidth,
            height: cHeight / imgHeight
          };
          // 以图画底
          ctx.drawImage(img, 0, 0, cWidth, cHeight);
          for (var i = 0; i < posx.length; i++) {
            ctx.fillStyle = '#00FF00';
            ctx.beginPath();
            ctx.arc(posx[i] * zoom.width, posy[i] * zoom.height, 5, 0, 2 * Math.PI);
            ctx.fill();
          }
          ;
          for (var j = 0; j < posx1.length; j++) {
            ctx.fillStyle = '#FF0000';
            ctx.beginPath();
            ctx.arc(posx1[j] * zoom.width, posy1[j] * zoom.height, 5, 0, 2 * Math.PI);
            ctx.fill();
          }
          ;
          for (var k = 0; k < posx2.length; k++) {
            ctx.fillStyle = '#FFD306';
            ctx.beginPath();
            ctx.arc(posx2[k] * zoom.width, posy2[k] * zoom.height, 5, 0, 2 * Math.PI);
            ctx.fill();
          }
        };
        this.animatePoints();
      })
      this.dataListLoading = false;
    },
    animatePoints() {
      const duration = 2000; // 动画持续时间为1000ms
      let startTime = null;

      const c = document.getElementById('myCanvas');
      const ctx = c.getContext('2d');
      const img = new Image();
      img.src = this.enabledMapLocalpaths;

      const cWidth = c.width;
      const cHeight = c.height;
      const imgWidth = img.naturalWidth;
      const imgHeight = img.naturalHeight;
      const zoom = {
        width: cWidth / imgWidth,
        height: cHeight / imgHeight
      };

      const step = (timestamp) => {
        if (!startTime) startTime = timestamp;
        let progress = (timestamp - startTime) / duration;
        if (progress > 1) progress = 1;

        ctx.clearRect(0, 0, c.width, c.height);

        // 重新渲染背景图像
        ctx.drawImage(img, 0, 0, cWidth, cHeight);

        for (const point of this.dataListInfo) {
          const oldPoint = this.oldDataListInfo.find(p => p.uuid === point.uuid) || point;
          const currentX = oldPoint.posX + (point.posX - oldPoint.posX) * progress;
          const currentY = oldPoint.posY + (point.posY - oldPoint.posY) * progress;

          ctx.beginPath();
          if (point.isWork == 1) {
            ctx.fillStyle = '#00FF00';
          } else if (point.isWork == 0) {
            ctx.fillStyle = '#FF0000';
          } else {
            ctx.fillStyle = '#FFD306';
          }
          ctx.arc(currentX * zoom.width, currentY * zoom.height, 5, 0, 2 * Math.PI);
          ctx.fill();
        }

        if (progress < 1) {
          requestAnimationFrame(step);
        }
      };

      img.onload = () => {
        requestAnimationFrame(step);
      };
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
}
#myCanvas {
  /*max-width: 100%;*/
  /*max-height: 100%;*/
  /*width:auto;*/
  /*height:auto;*/
}
.canvas-container {
  position: relative;
  width: 1500px;
  height: 680px;
}

.tooltip {
  position: absolute;
  background-color: white;
  border: 1px solid #ccc;
  padding: 5px;
  z-index: 1000;
  pointer-events: none;
  white-space: nowrap; /* 防止内容换行 */
}

#backgroundCanvas, #myCanvas {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

#myCanvas {
  z-index: 2;
}



</style>
